package com.itheima.stock.utils;

import org.apache.http.client.ClientProtocolException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class JosnJX {
    /**
     * 获取网络的json文件
     *
     * @param url
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String getJSONData(String url)
            throws ClientProtocolException, IOException {
        String result = "";
        URL url2 = null;
        try {
            url2 = new URL(url);
        } catch (MalformedURLException e) {
            System.out.println("getJSONData" + "MalformedURLException");
        }
        if (url2 != null) {
            try {
                // 使用HttpURLConnection打开连接
                HttpURLConnection urlConn = (HttpURLConnection) url2
                        .openConnection();
                urlConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
                urlConn.connect();
                String str = urlConn.getContentEncoding();
                InputStream is;
                if (str != null) {
                    if (str.equalsIgnoreCase("gzip")) {
                        is = new GZIPInputStream(urlConn.getInputStream());
                    } else {
                        is = urlConn.getInputStream();
                    }

                } else {
                    is = urlConn.getInputStream();
                }
                // 得到读取的内容
                InputStreamReader in = new InputStreamReader(is, "UTF-8");
                // 为输出创建BufferReader
                BufferedReader buffer = new BufferedReader(in);
                String inputLine = null;
                // 使用循环来读取获得的数据
                while ((inputLine = buffer.readLine()) != null) {
                    // 我们在每一行后面加\n
                    result += inputLine + "\n";
                }
                // 关闭Ihttp连接
                urlConn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}